/*
Copyright (c) 2009, Young Digital Planet SA
All rights reserved.

* Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this 
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Young Digital Planet SA nor the names of its 
  contributors may be used to endorse or promote products derived from this 
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
package pl.ydp.nexl.impl
{
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import flexunit.framework.TestCase;
	
	import mx.core.ByteArrayAsset;
	
	import pl.ydp.nexl.impl.air.NexlAirLibrary;
	import pl.ydp.nexl.plugin.resource.ILibraryResource;
	import pl.ydp.nexl.plugin.resource.ISwfLibraryResource;
	import pl.ydp.utils.Version;

	public class TestNexlLibrary extends TestCase
	{
		//
		[Embed(source="res/empty.swf",mimeType="application/octet-stream")]
		public static var EMPTY_LIB:Class;
		
		public static var LIBRARY:XML =
			<library version="1.0-beta/300">
				<activator class="some.activator.class" />
				<ext implementation="some.implemetation.1" id="e1">
					<attr name="type" value="some.type.1"/>
					
					<attr name="distinguisher" value="i1"/>
				</ext>
				<ext implementation="some.implemetation.2" id="e2">
					<attr name="type" value="some.type.1"/>
					
					<attr name="distinguisher" value="i2"/>
				</ext>
				<ext implementation="some.implemetation.3"  id="e3">
					<attr name="type" value="some.type"/>
					
					<attr name="distinguisher" value="i1"/>
					<attr name="distinguisher" value="i2"/>
				</ext>
				<ext implementation="some.implemetation.4"  id="e4">
					<attr name="type" value="some.type.2"/>
					
					<attr name="distinguisher" value="i5"/>
					<attr name="special" value="val"/>
				</ext>
			</library>;
		public static var EMPTY_LIBRARY:XML =
			<library>
			</library>;
		public static var EMPTY_LOCAL_LIBRARY:XML =
			<library loadType="local">
			</library>;
		public static var LIBRARY_WITH_RESOURCE:XML =
			<library>
				<resource id="r1" type="text">
				</resource>
				<resource id="r2" type="swf" src="empty.swf">
				</resource>
			</library>;
		public static var LIBRARY_WITH_RESOURCE_TUBELOC:XML =
			<library>
				<resource id="r1" type="text">
				</resource>
				<resource id="r2" type="swf" src="libs/as2_tubeloc.swf">
				</resource>
			</library>;
		public static var LIBRARY_WITH_SRC:XML =
			<library src="file.swf">
			</library>;
		
		public function testLoad():void {
			var lib:NexlLibrary = new NexlLibrary("");
			lib.loadData( LIBRARY );
			
			assertEquals( "Version", 0, new Version("1.0-beta/300").compare(lib.version) );
			assertEquals( "Activator class", "some.activator.class", lib.m_activatorClass );
			
			assertEquals( "Number of extensions", 4, lib.m_extensions.length );
			assertEquals( "Two extensions some.type.1", 2, lib.m_extensionsByType["some.type.1"].length );
			
			assertEquals( "Extension some.type.1[0]", "e1", lib.m_extensionsByType["some.type.1"][0].id );
			assertEquals( "Extension some.type.1[1]", "e2", lib.m_extensionsByType["some.type.1"][1].id );
			assertEquals( "Extension some.type[0]", "e3", lib.m_extensionsByType["some.type"][0].id );
			
			assertEquals( "Extension extensions[0]", "e1", lib.m_extensions[0].id );
			assertEquals( "Extension extensions[1]", "e2", lib.m_extensions[1].id );
			assertEquals( "Extension extensions[2]", "e3", lib.m_extensions[2].id );
		}
		
		public function testLoadEmpty():void {
			var lib:NexlLibrary = new NexlLibrary("");
			lib.loadData( EMPTY_LIBRARY );
			
			assertEquals( "Activator class", null, lib.m_activatorClass );
			assertEquals( "Number of extensions", 0, lib.m_extensions.length );
		}
		
		public function testSimpleFilter():void {
			var lib:NexlLibrary = new NexlLibrary("");
			lib.loadData( LIBRARY );
			
			var exts:Array = lib.list( {distinguisher: "i1"} );
			
			assertEquals( "{distinguisher=i1} There should be two extensions", 2, exts.length );
			assertEquals( "{distinguisher=i1} Extension extensions[0]", "e1", exts[0].id );
			assertEquals( "{distinguisher=i1}Extension extensions[1]", "e3", exts[1].id );
			
			exts = lib.list( {distinguisher: "i5"} );
			assertEquals( "{distinguisher=i5} There should be one extensions", 1, exts.length );
			assertEquals( "{distinguisher=i5} Extension extensions[0]", "e4", exts[0].id );
			
			exts = lib.list( {special: "val"} );
			assertEquals( "{special=val} There should be one extensions", 1, exts.length );
			assertEquals( "{special=val} Extension extensions[0]", "e4", exts[0].id );
		}
		
		public function testTypeFilter():void {
			var lib:NexlLibrary = new NexlLibrary("");
			lib.loadData( LIBRARY );
			
			var exts:Array = lib.list( {type: "some.type.1"} );
			assertEquals( "{type=some.type.1} There should be two extensions", 2, exts.length );
			assertEquals( "{type=some.type.1} Extension extensions[0]", "e1", exts[0].id );
			assertEquals( "{type=some.type.1} Extension extensions[1]", "e2", exts[1].id );
			
			exts = lib.list( {type: "some.type.1", distinguisher: "i1"} );
			assertEquals( "{type=some.type.1,distinguisher=i1} There should be two extensions", 1, exts.length );
			assertEquals( "{type=some.type.1} Extension extensions[0]", "e1", exts[0].id );
			
		}
		
		public function testMultipleLoads():void {
			var lib:NexlLibrary = new NexlLibrary("");
			lib.loadData( EMPTY_LOCAL_LIBRARY );
			var c1:Function = addAsync( function( ... rest ):void {
				trace( "loaded" ); 
				}, 100, null, 
				function():void {
					fail( "Library loaded callback never comes" ); 
				} );
			lib.loadLibrary( new LibLoadMonitor(c1) );
			var c2:Function = addAsync( function( ... rest ):void  {
				trace( "loaded2" );
				}, 100, null, 
				function():void {
					fail( "Call to loadLibrary, while it is loading, didn't give success information" ); 
				} );
			lib.loadLibrary( new LibLoadMonitor(c2) );
		}
		
		public function testMultipleLoadsUrl():void {
			var lib:NexlLibrary = new NexlLibrary(saveEmptyLib().url);
			lib.loadData( EMPTY_LIBRARY );
			var c1:Function = addAsync( function( ... rest ):void { }, 100, null, 
				function():void {
					fail( "Library loaded callback never comes" ); 
				} );
			lib.loadLibrary( new LibLoadMonitor(c1, function( ext:*, cause:String ):void {
				fail( "Library load failed '"+cause+"'" );
			} ) );
			var c2:Function = addAsync( function( ... rest ):void  { }, 100, null, 
				function():void {
					fail( "Call to loadLibrary, while it is loading, didn't give success information" ); 
				} );
			lib.loadLibrary( new LibLoadMonitor(c2) );
		}
		
		public function testResourceAir():void {
			saveEmptyLib();
			var airMain:NexlLibrary = new NexlAirLibrary(File.applicationStorageDirectory.resolvePath("empty.swf"), File.applicationStorageDirectory.resolvePath("empty.swf").parent );
			airMain.loadData( LIBRARY_WITH_RESOURCE );
			
			var swfLib:ILibraryResource = airMain.getLibraryResource( "r2" ); 
			assertTrue( "extension r2 should be ISwfLibraryResource", swfLib is ISwfLibraryResource );
			var swfLib2:ISwfLibraryResource = swfLib as ISwfLibraryResource;
			
			swfLib2.addEventListener( IOErrorEvent.IO_ERROR, addAsync( function(e:IOErrorEvent):void {
				fail( "IOError: "+e.text );
			}, 10, null, function(... a:*):void { } ) );
			swfLib2.domainImport();
			assertMatch("file imported to app domain", /^app:\/.*/, swfLib2.domainImportedSrc );
		}
		
		public function testResourceNet():void {
			var airMain:NexlLibrary = new NexlLibrary("/dev/mod/resource2/resource.php/94.1253086363/youTube.swf" );
			airMain.loadData( LIBRARY_WITH_RESOURCE_TUBELOC );
			
			var swfLib:ILibraryResource = airMain.getLibraryResource( "r2" ); 
			assertTrue( "extension r2 should be ISwfLibraryResource", swfLib is ISwfLibraryResource );
			var swfLib2:ISwfLibraryResource = swfLib as ISwfLibraryResource;
			
			swfLib2.addEventListener( IOErrorEvent.IO_ERROR, addAsync( function(e:IOErrorEvent):void {
				fail( "IOError: "+e.text );
			}, 10, null, function(... a:*):void { } ) );
			swfLib2.domainImport();
			assertEquals("file imported to app domain", "/dev/mod/resource2/resource.php/94.1253086363/libs/as2_tubeloc.swf", swfLib2.domainImportedSrc );
		}
		
		public function testBasePathToLibraryPath():void {
			var lib:NexlLibrary = new NexlLibrary( null, "http://localhost/dir/" );
			lib.loadData( LIBRARY_WITH_SRC );
			assertEquals( "resolved library file (base with slash)", "http://localhost/dir/file.swf", lib.libraryUrl );
			
			var lib2:NexlLibrary = new NexlLibrary( null, "http://localhost/dir" );
			lib2.loadData( LIBRARY_WITH_SRC );
			assertEquals( "resolved library file (base with slash)", "http://localhost/dir/file.swf", lib2.libraryUrl );
		}
		
		public static function saveEmptyLib():File {
			var dest:File = File.applicationStorageDirectory.resolvePath("empty.swf");
			
			var stream:FileStream = new FileStream();
			stream.open( dest, FileMode.WRITE );
			stream.writeBytes( (new EMPTY_LIB()) as ByteArrayAsset );
			stream.close();
			
			return dest;
		}
	}
}
	import pl.ydp.nexl.impl.ILibraryLoadMonitor;
	import pl.ydp.nexl.INexlLibrary;
	

class LibLoadMonitor implements ILibraryLoadMonitor {
	
	private var successCallback:Function;
	private var failCallback:Function;
	
	public function LibLoadMonitor( sc:Function, fl:Function = null ) {
		successCallback = sc;
		failCallback = fl;
	}
	
	public function failed( ext:INexlLibrary, cause:String = null ):void {
		failCallback( null );
	}
	
	public function succeeded( ext:INexlLibrary ):void {
		successCallback( null );
	}
}